<template>
  <div class="questions-new-container">
    <el-card>
      <div slot="header">{{ $route.query.id ? "试题修改" : "试题录入" }}</div>
      <el-form
        ref="formRef"
        :model="formData"
        label-width="80px"
        :rules="formRules"
      >
        <!-- 学科选择框 -->
        <el-form-item label="学科" prop="subjectID">
          <el-select
            v-model="formData.subjectID"
            placeholder="请选择"
            @change="getCatalogOptions"
          >
            <el-option
              v-for="item in subjectsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 目录选择框 -->
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="formData.catalogID" placeholder="请选择">
            <el-option
              v-for="item in catalogOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 企业选择框 -->
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="formData.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companyOptions"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 城市选择框 -->
        <el-form-item label="城市" prop="city">
          <el-select
            v-model="formData.province"
            placeholder="请选择"
            style="width: 198px"
            @change="getCityOptions"
          >
            <el-option
              v-for="item in provincesOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>

          <el-select
            v-model="formData.city"
            placeholder="请选择"
            style="width: 198px; margin-left: 4px"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 方向选择框 -->
        <el-form-item label="方向" prop="direction">
          <el-select v-model="formData.direction" placeholder="请选择">
            <el-option
              v-for="item in directionOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 题型单选框 -->
        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="formData.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value.toString()"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!-- 难度单选框 -->
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="formData.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value.toString()"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!-- 题干富文本编辑器 -->
        <el-form-item label="题干" prop="question">
          <quill-editor
            v-model="formData.question"
            :options="editorOptions"
            @change="checkValidateQuestion"
          ></quill-editor>
        </el-form-item>

        <!-- 选项编辑区 -->
        <el-form-item label="选项" v-if="formData.questionType !== '3'">
          <div
            v-for="item in formData.options"
            :key="item.code"
            style="margin-bottom: 20px"
          >
            <el-radio
              v-if="formData.questionType === '1'"
              v-model="item.isRight"
              :label="true"
              @change="handleRadioChange(item)"
              >{{ item.code }}</el-radio
            >
            <el-checkbox
              v-if="formData.questionType === '2'"
              v-model="item.isRight"
              :label="true"
              style="margin-right: 30px"
              >{{ item.code }}</el-checkbox
            >
            <el-input
              v-model="item.title"
              placeholder="请输入"
              style="width: 240px"
            ></el-input>
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :headers="{ Authorization: 'Bearer ' + token }"
              :show-file-list="false"
              :on-success="
                (res, file) => {
                  uploadSuccess(item, res, file);
                }
              "
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="item.img" :src="item.img" class="avatar" />
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <el-button
            type="danger"
            :disabled="formData.questionType !== '2'"
            size="small"
            @click="addOption"
            >+增加选项与答案</el-button
          >
        </el-form-item>

        <!-- 解析视频 -->
        <el-form-item label="解析视频">
          <el-input
            v-model="formData.videoURL"
            placeholder="请输入"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 答案解析富文本 -->
        <el-form-item label="答案解析" prop="answer">
          <quill-editor
            v-model="formData.answer"
            :options="editorOptions"
            @change="checkValidateAnswer"
          ></quill-editor>
        </el-form-item>

        <!-- 题目备注 -->
        <el-form-item label="题目备注">
          <el-input type="textarea" v-model="formData.remarks"></el-input>
        </el-form-item>

        <!-- 试题标签 -->
        <el-form-item label="试题标签">
          <el-select
            v-model="formData.tags"
            multiple
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="item in tagsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 确认提交按钮和确认修改按钮 -->
        <el-form-item>
          <el-button v-if="!$route.query.id" type="primary" @click="submitForm"
            >确认提交</el-button
          >
          <el-button v-else type="success" @click="updateForm"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 获取学科简单列表
import { simple as getSubjectsOptionsApi } from '@/api/hmmm/subjects.js'
// 获取目录简单列表
import { simple as getCatalogOptionsApi } from '@/api/hmmm/directorys.js'
// 获取公司目录列表
import { list as getCompanyOptionsApi } from '@/api/hmmm/companys.js'
// 和获取城市列表和地区列表
import { provinces as getProvincesOptionsApi, citys as getCityOptionsApi } from '@/api/hmmm/citys.js'
// 导入方向选项,题型,难度
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 导入添加表单,更新表单,获取表单详情方法
import { add as submitFormApi, update as updateFormApi, detail as getFormDetailApi } from '@/api/hmmm/questions.js'
// 导入获取标签简单列表的方法
import { simple as getTagsOptionsApi } from '@/api/hmmm/tags.js'
// 导入获取token的方法
import { getToken } from '@/utils/auth.js'

export default {
  data () {
    return {
      token: getToken(),
      // 表单数据对象
      formData: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: []
      },
      // 表单校验规则
      formRules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择公司', trigger: 'change' }],
        city: [{ required: true, message: '选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]
      },
      // 学科选项
      subjectsOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      companyOptions: [],
      // 城市选项
      provincesOptions: [],
      // 城市下地区选项
      cityOptions: [],
      // 方向选项
      directionOptions: direction,
      // 题型
      questionType: questionType,
      // 难度
      difficulty: difficulty,
      // 标签选项
      tagsOptions: [],
      // 富文本编辑的配置项
      editorOptions: {
        placeholder: '请输入',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ list: 'ordered' }, { list: 'bullet' }],
              ['blockquote', 'code-block'],
              ['image', 'link']
            ]
          }
        }
      }
    }
  },
  created () {
    // 获取学科选项
    this.getSubjectsOptions()
    // 获取公司选项
    this.getCompanyOptions()
    // 获取城市列表
    this.getProvincesOptions()
    if (this.$route.query.id) {
      this.getFormDetail()
    }
  },
  watch: {
    '$route.query' () {
      if (this.$route.query.id) {
        this.getFormDetail()
      }
    }
  },
  methods: {
    // 获取学科选项
    async getSubjectsOptions () {
      const { data } = await getSubjectsOptionsApi()
      this.subjectsOptions = data
    },
    // 获取目录选项,在获取到学科选项时的change事件触发
    async getCatalogOptions () {
      // 点击其他学科会保留上一次点击的学科的目录
      this.formData.catalogID = ''
      const { data } = await getCatalogOptionsApi({ subjectID: this.formData.subjectID })
      console.log('目录列表', data)
      this.catalogOptions = data
      // 点击其他学科会保留上一次点击的学科的标签
      this.formData.tags = ''
      const res = await getTagsOptionsApi({ subjectID: this.formData.subjectID })
      console.log(res)
      this.tagsOptions = res.data
    },
    // 获取公司选项
    async getCompanyOptions () {
      const { data } = await getCompanyOptionsApi({ pagesize: 10000 })
      // console.log(data)
      this.companyOptions = data.items
    },
    // 获取城市选项
    getProvincesOptions () {
      this.provincesOptions = getProvincesOptionsApi()
      // console.log(this.formData.province)
    },
    // 获取城市下地区选项
    getCityOptions () {
      this.formData.city = ''
      this.cityOptions = getCityOptionsApi(this.formData.province)
    },
    // 监听选项编辑区单选框的改变
    handleRadioChange (item) {
      // 将所有选项的isRight改为false,在将当前选项的isRight改为true
      this.formData.options.forEach(item => {
        item.isRight = false
      })
      item.isRight = true
    },
    // 增加选项与答案
    addOption () {
      // 规律：
      // 索引 0 ---> A  ascii  65
      // 索引 1 ---> B  ascii  66
      // 索引 2 ---> C  ascii  67
      // 索引 3 ---> D  ascii  68
      // 索引 4 ---> E  ascii  69
      // ...
      // 总结 code = String.fromCharCode(index + 65)
      this.formData.options.push({
        code: String.fromCharCode(65 + this.formData.options.length),
        title: '',
        img: '',
        isRight: false
      })
    },
    // 提交表单
    async submitForm () {
      try {
        await this.$refs.formRef.validate()
        this.formData.tags = this.formData.tags.join(',')
        await submitFormApi(this.formData)
        this.$message.success('提交成功')
        this.$router.push('/questions/list')
        this.$refs.formRef.resetFields()
        this.formData = {
          // 学科
          subjectID: '',
          // 目录
          catalogID: '',
          // 企业
          enterpriseID: '',
          // 城市
          province: '',
          // 地区
          city: '',
          // 方向
          direction: '',
          // 题型
          questionType: '1',
          // 难度
          difficulty: '1',
          // 题干
          question: '',
          // 选项
          options: [
            {
              code: 'A',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'B',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'C',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'D',
              title: '',
              img: '',
              isRight: false
            }
          ],
          // 解析视频
          videoURL: '',
          // 答案解析
          answer: '',
          // 题目备注
          remarks: '',
          // 试题标签
          tags: []
        }
      } catch (error) {
        console.log(error)
        this.$message.error('提交失败')
      }
    },
    // 监听图片上传成功的事件
    // uploadSuccess 不带括号  接收默认参数
    // uploadSuccess 带了括号  接收自己传入参数
    uploadSuccess (item, res, file) {
      console.log(item, res, file)
      // res 是响应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      // this.img = URL.createObjectURL(file.raw)
      item.img = URL.createObjectURL(file.raw)
    },
    // 对图片格式进行校验
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 保存修改
    async updateForm () {
      try {
        await this.$refs.formRef.validate()
        this.formData.tags = this.formData.tags.join(',')
        await updateFormApi(this.formData)
        this.$message.success('修改成功')
        this.$router.push('/questions/list')
        this.formData = {
          // 学科
          subjectID: '',
          // 目录
          catalogID: '',
          // 企业
          enterpriseID: '',
          // 城市
          province: '',
          // 地区
          city: '',
          // 方向
          direction: '',
          // 题型
          questionType: '1',
          // 难度
          difficulty: '1',
          // 题干
          question: '',
          // 选项
          options: [
            {
              code: 'A',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'B',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'C',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'D',
              title: '',
              img: '',
              isRight: false
            }
          ],
          // 解析视频
          videoURL: '',
          // 答案解析
          answer: '',
          // 题目备注
          remarks: '',
          // 试题标签
          tags: []
        }
      } catch (error) {
        console.log(error)
        this.$message.error('修改失败')
      }
    },
    // 获取试题表单详情
    async getFormDetail () {
      const { data } = await getFormDetailApi()
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.formData = data
      const res = await getCatalogOptionsApi({ subjectID: this.formData.subjectID })
      this.catalogOptions = res.data
      const res2 = await getTagsOptionsApi({ subjectID: this.formData.subjectID })
      this.tagsOptions = res2.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 对富文本编辑器进行校验
    checkValidateQuestion () {
      this.$refs.formRef.validateField('question')
    },
    checkValidateAnswer () {
      this.$refs.formRef.validateField('answer')
    }
  }
}
</script>

<style scoped lang="scss">
.questions-new-container {
  padding: 10px 10px;
}
.el-select {
  width: 400px;
}
.avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
  margin-left: 4px;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
</style>
